<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        div {
            position: relative;
            width: 100px;
            height: 100px;
            background-color: paleturquoise;
        }
    </style>
</head>

<body>
    <div></div>
    <button class="btn1">点击后移动到500</button>
    <button class="btn2">点击后移动到800</button>
    <script>
        function animate(obj, target,callback) {
            clearInterval(obj.timer);       //保证只会有一个定时器在工作
            obj.timer = setInterval(function () {
                var step = (target - obj.offsetLeft) / 10;//取整操作,距离若为负值，则向下取整，若为正值，则向上取整
                step = step > 0 ? Math.ceil(step) : Math.floor(step);
                if (obj.offsetLeft == target) {
                    clearInterval(obj.timer);
                    if(callback){            //在定时器结束时执行回调函数
                        callback();
                    }
                }
                obj.style.left = obj.offsetLeft + step + 'px';
            }, 30)
        }
        var box = document.querySelector('div');
        var btn1 = document.querySelector('.btn1');
        var btn2 = document.querySelector('.btn2');
        btn1.addEventListener('click', function () {
            animate(box, 500,function(){
                box.style.backgroundColor = 'pink';
            });
        })
        btn2.addEventListener('click', function () {
            animate(box, 800);
        })


    </script>
</body>

</html>